<template>
  <van-form validate-trigger="onBlur" :model="registerForm" @submit="handleRegister">
    <van-cell-group inset>
      <van-field
        v-model="registerForm.email"
        name="email"
        left-icon="envelop-o"
        label="QQ邮箱"
        placeholder="QQ邮箱"
        @@update:model-value="(value) => updateLoginForm('email', value)"
        :rules="registerRules.email"
      />
      <transition name="fade">
        <div v-if="isValidQQEmail" class="qrcode-container">
          <img :src="qrimage1" alt="注册二维码" class="register-qrcode" />
          <div class="qrcode-tips">
            <p class="qrcode-tip">入群的QQ需和邮箱为同一账号</p>
            <p class="qrcode-tip">加群验证，即可完成激活</p>
            <p class="qrcode-tip">再点击注册即可成功注册</p>
          </div>
        </div>
      </transition>
      <van-field
        v-model="registerForm.password"
        left-icon="records-o"
        type="password"
        name="password"
        label="密码"
        @@update:model-value="(value) => updateLoginForm('password', value)"
        placeholder="请输入密码!"
        :rules="registerRules.password"
      />
      <van-field
        v-model="displayRegisterToken"
        left-icon="lock"
        name="token"
        label="注册令牌"
        placeholder="请先获取注册令牌"
        :rules="registerRules.token"
        readonly
      >
        <template #button>
          <van-button
            size="small"
            type="primary"
            :loading="tokenLoading"
            @click="getRegistrationToken"
          >
            获取令牌
          </van-button>
        </template>
      </van-field>
    </van-cell-group>

    <div style="margin: 16px 16px 0;">
      <van-checkbox v-model="agreePrivacy" shape="square" icon-size="16px">
        <span style="font-size: 12px;">我已阅读并同意 <a href="https://seerxin.com/url/ua" target="_blank" style="color: var(--van-primary-color);">用户隐私协议</a></span>
      </van-checkbox>
    </div>

    <div style="margin: 16px">
      <van-button :loading="isLoading" :disabled="!agreePrivacy" round block type="primary" native-type="submit">
        注册
      </van-button>
    </div>
  </van-form>
</template>

<script setup>
import { reactive, defineProps, watch, ref, computed } from 'vue'
import _ from 'lodash-es'
import { sendCaptcha, register, generateRegisterToken } from '@/api/user'
import { showNotify, Checkbox as VanCheckbox } from 'vant' // Import Checkbox
const emailPattern = /[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/
const qrimage1 = ref('/go/check/image')

const props = defineProps({
  tabActive: {
    type: Number,
    required: true,
    default: 0
  }
})

watch(
  () => props.tabActive,
  (newVal, oldVal) => {
    if (newVal !== oldVal) {
      registerForm.email = ''
      registerForm.password = ''
      registerForm.captcha = ''
      registerForm.token = ''
    }
  }
)

const isLoading = ref(false)
const agreePrivacy = ref(false); // Add state for privacy agreement
// 验证码相关
const countDown = ref(0)
const isGetCode = ref(false)
let timer = null // 将timer提升到组件作用域
// 令牌相关
const tokenLoading = ref(false)
const canSendCode = ref(true)
// 注册表单
const registerForm = reactive({
  email: '',
  password: '',
  captcha: '',
  token: ''
})

// 计算属性：显示令牌的前4位，其余用*代替
const displayRegisterToken = computed({
  get() {
    if (!registerForm.token) return '';
    return registerForm.token.substring(0, 4);
  },
  set(value) {
    registerForm.token = value;
  }
});
const isValidQQEmail = computed(() => {
  // 检查是否是QQ邮箱格式
  const qqEmailPattern = /^[1-9][0-9]{4,}@qq\.com$/i;
  return qqEmailPattern.test(registerForm.email);
});

// 注册表单验证规则
const registerRules = reactive({
  email: [
    {
      required: true,
      message: '邮箱不能为空',
      validator: (value) => {
        if (!emailPattern.test(value)) {
          return '邮箱格式不正确'
        } else {
          return
        }
      }
    }
  ],
  captcha: [
    {
      required: true,
      message: '验证码不能为空',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码' },
    { min: 6, max: 20, message: '密码不能超过20位' }
  ],
  token: [
    { required: true, message: '请输入注册令牌' }
  ]
})
const updateLoginForm = (key, value) => {
  emit('update:registerForm', { ...(props.loginForm || {}), [key]: value })
}
// 验证码发送的核心逻辑
const sendCodeCore = async () => {
  try {
    // 验证邮箱格式
    if (!emailPattern.test(registerForm.email)) {
      showNotify({
        type: 'warning',
        message: '请输入正确的邮箱格式'
      })
      return
    }

    // 如果已经在倒计时中，不允许重复发送
    if (countDown.value > 0) {
      return
    }

    // 清除可能存在的旧定时器
    if (timer) {
      clearInterval(timer)
    }

    // 立即禁用按钮并开始倒计时
    countDown.value = 60

    // 立即开始倒计时
    timer = setInterval(() => {
      if (countDown.value > 0) {
        countDown.value--
      } else {
        clearInterval(timer)
        timer = null
      }
    }, 1000)

    let json = {
      email: registerForm.email,
      scene: 'register'
    }

    // 调用发送验证码接口
    const res = await sendCaptcha(json)
    if (res.code === 200) {
      showNotify({
        type: 'success',
        message: '验证码已发送，请查收'
      })
      isGetCode.value = true
    } else {
      showNotify({
        type: 'danger',
        message: res.msg || '验证码发送失败'
      })
      isGetCode.value = false
    }
  } catch (error) {
    isGetCode.value = false
  }
}

// 使用防抖包装的获取验证码函数
const getCode = _.debounce(sendCodeCore, 300)

// 获取注册令牌
const getRegistrationToken = async () => {
  try {
    // 验证邮箱格式
    if (!emailPattern.test(registerForm.email)) {
      showNotify({
        type: 'warning',
        message: '请输入正确的邮箱格式'
      })
      return
    }

    // 验证密码
    if (!registerForm.password || registerForm.password.length < 6) {
      showNotify({
        type: 'warning',
        message: '请输入至少6位密码'
      })
      return
    }

    tokenLoading.value = true
    const res = await generateRegisterToken({
      email: registerForm.email,
      password: registerForm.password
    })

    if (res.code === 200) {
      registerForm.token = res.token
      showNotify({
        type: 'success',
        message: '注册令牌获取成功'
      })
    } else {
      showNotify({
        type: 'danger',
        message: res.msg || '获取注册令牌失败'
      })
    }
  } catch (error) {
    console.error('获取注册令牌失败:', error)
    showNotify({
      type: 'danger',
      message: error.msg || '获取注册令牌失败，请稍后重试'
    })
  } finally {
    tokenLoading.value = false
  }
}

// 表单验证逻辑
const validateForm = () => {
  const errors = [];
  if (!registerForm.email) {
    errors.push('邮箱不能为空');
  } else if (!emailPattern.test(registerForm.email)) {
    errors.push('邮箱格式不正确');
  }
  if (!registerForm.password) {
    errors.push('请输入密码');
  } else if (registerForm.password.length < 6 || registerForm.password.length > 20) {
    errors.push('密码长度需在6到20位之间');
  }
  if (!registerForm.token) {
    errors.push('请输入注册令牌');
  }
  return errors;
};

// 注册处理
const handleRegister = async () => {
  if (!agreePrivacy.value) {
    showNotify({
      type: 'warning',
      message: '请先阅读并同意用户隐私协议'
    });
    return;
  }

  const errors = validateForm();
  if (errors.length > 0) {
    showNotify({
      type: 'danger',
      message: errors[0]
    });
    return;
  }

  try {
    isLoading.value = true;
    const res = await register({
      email: registerForm.email,
      password: registerForm.password,
      token: registerForm.token
    });

    if (res.code === 200) {
      showNotify({
        type: 'success',
        message: '注册成功'
      });
      // 切换到登录模式或其他逻辑
    } else {
      showNotify({
        type: 'danger',
        message: res.msg || '注册失败'
      });
    }
  } catch (error) {
    console.error('注册失败:', error);
    showNotify({
      type: 'danger',
      message: error.msg || '注册失败，请稍后重试'
    });
  } finally {
    isLoading.value = false;
  }
};
</script>
<style>
.qrcode-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 16px;
}

.register-qrcode {
  width: 150px;
  height: 150px;
  margin-bottom: 12px;
  border: 2px solid #eee;
  border-radius: 8px;
}

.qrcode-tips {
  text-align: center;
  font-size: 14px;
  color: #666;
  line-height: 1.6;
}

.qrcode-tip {
  margin: 4px 0;
}
</style>
